package com.kangye.learnteacher.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kangye.learnteacher.entity.Classes;
import com.kangye.learnteacher.entity.Grade;
import com.kangye.learnteacher.entity.Role;
import com.kangye.learnteacher.entity.User;
import com.kangye.learnteacher.mapper.StageMapper;
import com.kangye.learnteacher.mapper.UserMapper;
import com.kangye.learnteacher.service.UserService;
import com.kangye.learnteacher.util.ExcelImportUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.util.ResourceUtils;

import javax.annotation.Resource;
import java.io.*;
import java.util.*;
import java.util.List;

/**
 * (User)表服务实现类
 *
 * @author makejava
 * @since 2021-05-17 15:49:53
 */
@Service("userService")
public class UserServiceImpl implements UserService {
    /**
     * 用户表数据访问
     */
    @Resource
    private UserMapper userDao;

    /**
     * 阶段数据访问
     */
    @Resource
    private StageMapper stageMapper;

    /**
     * excel文件验证
     */
    @Autowired
    private ExcelImportUtils excelImportUtils;

    /**
     * 通过ID查询单条数据
     *
     * @param userId 主键
     * @return 实例对象
     */
    @Override
    public User queryById(Integer userId) {
        return this.userDao.queryById(userId);
    }

    /**
     * 查询多条数据
     *
     * @param page 查询起始位置
     * @param limit  查询条数
     * @param user  实例对象
     * @return 对象列表
     */
    @Override
    public PageInfo<User> queryAllByLimit(int page, int limit, User user) {
        //分页查询 , pageNum 当前页 pageSize 每页n条数据
        PageHelper.startPage(page,limit);
        List<User> list = this.userDao.queryAll(user);
        //查询结果存放info中
        PageInfo<User> info = new PageInfo<>(list);
        return info;
    }

    /**
     * 插入单条数据
     *
     * @param user 实例对象
     * @return 是否成功
     */
    @Override
    public boolean insert(User user) {
        return this.userDao.insert(user)>0;
    }

    /**
     * 修改数据
     *
     * @param user 实例对象
     * @return 是否成功
     */
    @Override
    public boolean update(User user) {
        return this.userDao.update(user)>0;
    }

    /**
     * 通过主键删除数据
     *
     * @param userId 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer userId) {
        return this.userDao.deleteById(userId) > 0;
    }

    /**
     * 年级查询
     * @param gradeId   主键
     * @return  对象列表
     */
    @Override
    public List<Grade> gradeList(Integer gradeId) {
        return userDao.gradeList(gradeId);
    }

    /**
     * 角色查询
     * @param roleId 主键
     * @return  对象列表
     */
    @Override
    public List<Role> roleList(Integer roleId) {
        return userDao.roleList(roleId);
    }

    /**
     * 创建文件
     * @param fileName 文件名
     * @param file 文件流
     */
    @Override
    public String batchImport(String fileName, MultipartFile file) {
        File uploadDir = null;
        try {
            uploadDir = new File(ResourceUtils.getURL("classpath:").getPath());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        //创建一个目录 （它的路径名由当前 File 对象指定，包括任一必须的父路径。）
        if (!uploadDir.exists()) uploadDir.mkdirs();
        //新建一个临时文件
        File tempFile = new File("E:\\" + UUID.randomUUID() + ".xlsx");
        //初始化输入流
        InputStream is = null;
        try {
            //将上传的文件写入新建的文件中
            file.transferTo(tempFile);

            //根据新建的文件实例化输入流
            is = new FileInputStream(tempFile);

            //根据版本选择创建Workbook的方式
            Workbook wb = null;
            //根据文件名判断文件是2003版本(.xls)还是2007版本(.xlsx)
            if (excelImportUtils.isExcel2007(fileName)) {
                wb = new XSSFWorkbook(is);
            } else {
                wb = new HSSFWorkbook(is);
            }
            //根据excel里面的内容读取知识库信息
            return readExcelValue(wb, tempFile);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    is = null;
                    e.printStackTrace();
                }
            }
        }
        return "文件类型错误!请重新下载模板";
    }

    /**
     * 解析Excel里面的数据
     *
     * @param wb
     * @param tempFile
     * @return  提示信息
     */
    private String readExcelValue(Workbook wb, File tempFile) {
        //对象列表，存储从excel表中读取的数据
        List<User> userList = new ArrayList<>();
        //错误信息接收器
        String errorMsg = "";
        //得到第一个shell
        Sheet sheet = wb.getSheetAt(0);
        //得到Excel的行数
        int totalRows = sheet.getPhysicalNumberOfRows();
        //循环Excel行数,从第二行开始。标题不入库
        for (int r = 1; r < totalRows; r++) {
            Row row = sheet.getRow(r);
            if (row == null) {
                //跳过空行
                continue;
            }
            //创建user对象
            User user = new User();
            //循环Excel的列
            try {
                //年级判空
                if (row.getCell(0).toString()==null || row.getCell(0).toString() ==""){
                    errorMsg = "第" + (r + 1) + "年级不能为空!请修改后在上传";
                    tempFile.delete();
                    return errorMsg;
                }
                Grade grade = stageMapper.selectByName(row.getCell(0).toString());
                user.setUserGradeId(grade.getGradeId());

                //班级判空
                if (row.getCell(1).toString()==null || row.getCell(1).toString() ==""){
                    errorMsg = "第" + (r + 1) + "班级不能为空!请修改后在上传";
                    tempFile.delete();
                    return errorMsg;
                }
                Classes classes = stageMapper.selectName(row.getCell(1).toString());
                user.setUserClassesId(classes.getClassesId());

                row.getCell(2).setCellType(CellType.STRING);
                String username = row.getCell(2).toString();
                //判断用户名是否重复，是否为空
                if (username == null || username == ""){
                    //提示信息
                    errorMsg = "第" + (r + 1) + "用户名不能为空!请修改后在上传";
                    //删除临时文件
                    tempFile.delete();
                    return errorMsg;
                }else if (userDao.queryByUsername(username).get(0).equals(null)){
                    user.setUserUserName(row.getCell(2).toString());
                } else{
                    errorMsg = "第" + (r + 1) + "用户名重复!请修改后在上传";
                    tempFile.delete();
                    return errorMsg;
                }

                //过期，替换解决方案
                row.getCell(3).setCellType(CellType.STRING);
                //判断密码判空
                if (row.getCell(3).toString() == null || row.getCell(3).toString() == ""){
                    errorMsg = "第" + (r + 1) + "密码不能为空!请修改后在上传";
                    tempFile.delete();
                    return errorMsg;
                }else if (row.getCell(3).toString().length()<6){
                    errorMsg = "第" + (r + 1) + "密码至少为六位!请修改后在上传";
                    tempFile.delete();
                    return errorMsg;
                }
                user.setUserPassword(row.getCell(3).toString());
                //姓名
                row.getCell(4).setCellType(CellType.STRING);
                user.setUserRealName(row.getCell(4).toString());
                //年龄
                row.getCell(5).setCellType(CellType.STRING);
                user.setUserAge(Integer.parseInt(row.getCell(5).toString()));
                //性别
                row.getCell(6).setCellType(CellType.STRING);
                if (row.getCell(6).toString().equals("男")){
                    user.setUserGender(1);
                }else if(row.getCell(6).toString()==null || row.getCell(6).toString().equals("")){
                    user.setUserGender(null);
                }else {
                    user.setUserGender(0);
                }
                row.getCell(7).setCellType(CellType.STRING);
                user.setUserPhone(row.getCell(7).toString());
                //出生日期
                row.getCell(8).setCellType(CellType.STRING);
                user.setUserBirthday(row.getCell(8).toString());
                //头像
                row.getCell(9).setCellType(CellType.STRING);
                user.setUserHeadLogo(row.getCell(9).toString());
                //角色
                user.setUserRoleId(3);
                //创建时间
                user.setUserCreateTime(new Date());
            } catch (NullPointerException e) {
                errorMsg = "第" + (r + 1) + "行数据出错!请修改后在上传";
                tempFile.delete();
                return errorMsg;
            }
            userList.add(user);
        }
        //删除上传的临时文件
        if (tempFile.exists()) {
            tempFile.delete();
        }
        //遍历添加数据
        for (User i : userList) {
            insert(i);
        }
        errorMsg = "上传完成";
        return errorMsg;
    }
}
